package com.example.service.impl;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.example.exchange.BPWebService;
import com.example.dao.UxJbcardMapper;
import com.example.dao.UxenglstMapper;
import com.example.dao.UxmadsMapper;
import com.example.dao.UxpmStckMapper;
import com.example.entity.Drawing;
import com.example.entity.DrawingMaterial;
import com.example.entity.JB2HSSE;
import com.example.entity.JB3QCD;
import com.example.entity.JOBCard;
import com.example.entity.JobcardWeIdListMA;
import com.example.entity.JobcardWeIdListPI;
import com.example.entity.JobcardWeIdListST;
import com.example.entity.Material2;
import com.example.entity.MaterialPart;
import com.example.entity.PartMaterialDetail;
import com.example.entity.ProjectShell;
import com.example.entity.RequiredMaterialDetail;
import com.example.entity.SchedulePlanEngineering;
import com.example.entity.SurplusMaterial;
import com.example.exchange.BPConstants;
import com.example.exchange.MapUtils;
import com.example.exchange.ServiceUtil;
import com.example.exchange.XMLHeaderConstants;
import com.example.util.XMLResUtil;

import net.sf.json.JSONObject;

import com.example.exchange.XMLObject;
import com.example.dao.*;

public class Util {

	@Autowired
	public UxpmStckMapper uxpmStck;
	@Autowired
	public UxmadsMapper uxmadsMapper;
	@Autowired
	public UxenglstMapper uxenglstMapper;
	@Autowired
	public UxJbcardMapper uxJbcardMapper;
	@Autowired
	public ProjectInfoMapper projectInfoMapper;

	BPWebService webservice = null;

	/**
	 * 插入物料接口
	 *
	 * @param indexs
	 * @param uxpmStck
	 * @param discipline
	 * @param materialSort
	 */
	public void insertMaterials(Set<Map<String, String>> data, String discipline, String materialSort,
			Integer projectNumber) {

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		String date = df.format(new Date());
		Integer maxId = uxpmStck.select_UxpmstckMaxID(); // 获取最大ID
		if (maxId == null) {
			maxId = 0;
		}
		maxId++;
		List<Map<String, String>> indexs = this.deweightMaterial(data, materialSort, discipline, projectNumber);// 将物料信息去重
		for (int i = 0; i < indexs.size() / 900 + 1; i++) {// 一次提交所有数据等待时间太久 分割开来提交
			List<Map<String, String>> index = new ArrayList<Map<String, String>>();
			if ((i + 1) * 900 > indexs.size())
				index = indexs.subList(i * 900, indexs.size());
			if ((i + 1) * 900 <= indexs.size())
				index = indexs.subList(i * 900, (i + 1) * 900);
			if (index.size() > 0) {
				uxpmStck.insertUxpmstck_ListMap(index, date, maxId, discipline, materialSort, projectNumber); // discipline
				// 解析专业表格插物料材信息
				uxpmStck.insertUxpmstck_PERM_ListMap(index, maxId);// 插入相应数据权限
				maxId = maxId + index.size();
			}
		}
		if (materialSort.equals("part")) { // 将零件信息插入零件BP
			maxId = uxpmStck.select_UxmateptMaxId();
			if (maxId == null) {
				maxId = 0;
			}
			maxId++;
			for (int i = 0; i < indexs.size() / 900 + 1; i++) {// 一次提交所有数据等待时间太久 分割开来提交
				System.err.println(i);
				List<Map<String, String>> index = new ArrayList<Map<String, String>>();
				if ((i + 1) * 900 > indexs.size())
					index = indexs.subList(i * 900, indexs.size());
				if ((i + 1) * 900 <= indexs.size())
					index = indexs.subList(i * 900, (i + 1) * 900);
				if (index.size() > 0) {
					try {
						uxpmStck.insertUxmatept(index, maxId, projectNumber);
						maxId = maxId + index.size();
					} catch (Exception e) {
						for(Map<String, String> map :index) {
							List<Map<String, String>> maps = new ArrayList<Map<String, String>>();
							maps.add(map);
							try {
								uxpmStck.insertUxmatept(maps, maxId, projectNumber);
								maxId = maxId + maps.size();
							} catch (Exception e2) {
								System.err.println(maps);
							}

						}
 					}


				}
			}
		}

		// 将母材信息插入项目级母材表
		if (materialSort.equals("bulk") || materialSort.equals("tag") || materialSort.equals("fabrication")) {
			maxId = uxpmStck.select_UxmateMaxID();
			if (maxId == null) {
				maxId = 1;
			} else {
				maxId++;
			}
			for (int i = 0; i < indexs.size() / 900 + 1; i++) {// 一次提交所有数据等待时间太久 分割开来提交
				List<Map<String, String>> index = new ArrayList<Map<String, String>>();
				if ((i + 1) * 900 > indexs.size())
					index = indexs.subList(i * 900, indexs.size());
				if ((i + 1) * 900 <= indexs.size())
					index = indexs.subList(i * 900, (i + 1) * 900);
				if (index.size() > 0) {
					uxpmStck.insertUxmate_ListMap(index, date, maxId, discipline, materialSort, projectNumber);
					uxpmStck.insertUxmate_PERM_ListMap(index, maxId);
					maxId = maxId + index.size();
				}
			}

		}

		// 将母材信息插入公司级母材表
		if (materialSort.equals("bulk")) {
			maxId = uxpmStck.select_Uxmatex3MaxID();
			if (maxId == null) {
				maxId = 0;
			}
			maxId++;
			for (int i = 0; i < indexs.size() / 900 + 1; i++) {// 一次提交所有数据等待时间太久 分割开来提交
				System.err.println(i);
				List<Map<String, String>> index = new ArrayList<Map<String, String>>();
				if ((i + 1) * 900 > indexs.size())
					index = indexs.subList(i * 900, indexs.size());
				if ((i + 1) * 900 <= indexs.size())
					index = indexs.subList(i * 900, (i + 1) * 900);
				if (index.size() > 0) {
					uxpmStck.insertUxmatex3_Company_ListMap(index, date, maxId, discipline, materialSort);
					uxpmStck.insertUxmatex3_PERM_ListMap(index, maxId);
					maxId = maxId + index.size();
				}
			}

		}

	}

	public void insertdrawingMaterialsPI(Map<String, DrawingMaterial> drawingMaterialsMap, String discipline,
			Integer projectNumber) {
		List<DrawingMaterial> drawingMaterials = new ArrayList<DrawingMaterial>();
		Set<Material2> material2s = new HashSet<Material2>();

		List<String> list = uxmadsMapper.select_unifier_uxmads_Drawing_No(discipline, projectNumber);

		Integer maxId = uxmadsMapper.select_unifier_uxmads_MaxId();

		if (maxId == null) {
			maxId = 1;
		}
		maxId++;
		for (DrawingMaterial index : drawingMaterialsMap.values()) { // 将所有的 图纸关联物料对象取出
			index.setId(maxId);
			drawingMaterials.add(index);
			maxId++;
		}
		System.err.println("图纸物料关系信息去重前" + drawingMaterials.size()); //
		drawingMaterials = drawingMaterials.stream().filter(i -> !list.contains(i.getDrawing_No() + i.getRev()))
				.collect(Collectors.toList());
		System.err.println("图纸物料关系信息去重后" + drawingMaterials.size());

		for (DrawingMaterial index : drawingMaterials) {
			for (Material2 index2 : index.getMaterials()) {
				index2.setDrawing_No(index.getDrawing_No());
				index2.setId(index.getId());
			}
			material2s.addAll(index.getMaterials());
		}

		System.err.println(" 物料关系信息去重前" + material2s.size());
		List<Material2> distinctClass = material2s.stream()
				.collect(Collectors.collectingAndThen(
						Collectors.toCollection(
								() -> new TreeSet<>(Comparator.comparing(o -> o.getId() + ";" + o.getMaterial_Code()))),
						ArrayList::new)); // 将物料信息去重
		System.err.println(" 物料关系信息去重后" + distinctClass.size());

		for (int i = 0; i < drawingMaterials.size() / 900 + 1; i++) {// 一次提交所有数据等待时间太久 分割开来提交
			List<DrawingMaterial> index = new ArrayList<DrawingMaterial>();
			if ((i + 1) * 900 > drawingMaterials.size())
				index = drawingMaterials.subList(i * 900, drawingMaterials.size());
			if ((i + 1) * 900 <= drawingMaterials.size())
				index = drawingMaterials.subList(i * 900, (i + 1) * 900);
			if (index.size() > 0) {
				uxmadsMapper.insert_Uxmads(index, projectNumber);
			}
		}
		maxId = uxmadsMapper.select_unifier_uxmads_lieitem_MaxId();
		if (maxId == null) {
			maxId = 1;
		} else {
			maxId++;
		}
		List<Material2> indexs = new ArrayList<Material2>(distinctClass);
		for (int i = 0; i < indexs.size() / 900 + 1; i++) {// 一次提交所有数据等待时间太久 分割开来提交
			List<Material2> index = new ArrayList<Material2>();
			if ((i + 1) * 900 > indexs.size())
				index = indexs.subList(i * 900, indexs.size());
			if ((i + 1) * 900 <= indexs.size())
				index = indexs.subList(i * 900, (i + 1) * 900);
			if (index.size() > 0) {
				uxmadsMapper.insert_Uxmads_lieitem(index, maxId);
				maxId = maxId + index.size();
			}
		}

	}

	public void insertdrawingMaterialsMA(Map<String, DrawingMaterial> drawingMaterialsMap, String discipline,
			Integer projectNumber) {
		List<DrawingMaterial> drawingMaterials = new ArrayList<DrawingMaterial>();
		Set<Material2> material2s = new HashSet<Material2>();

		List<String> list = uxmadsMapper.select_unifier_uxmads_Drawing_No(discipline, projectNumber);

		Integer maxId = uxmadsMapper.select_unifier_uxmads_MaxId();

		if (maxId == null) {
			maxId = 1;
		}
		maxId++;
		for (DrawingMaterial index : drawingMaterialsMap.values()) { // 将所有的 图纸关联物料对象取出
			index.setId(maxId);
			drawingMaterials.add(index);
			maxId++;
		}
		System.err.println("图纸物料关系信息去重前" + drawingMaterials.size()); //
		drawingMaterials = drawingMaterials.stream().filter(i -> !list.contains(i.getDrawing_No() + i.getRev()))
				.collect(Collectors.toList());
		System.err.println("图纸物料关系信息去重后" + drawingMaterials.size());

		for (DrawingMaterial index : drawingMaterials) {
			for (Material2 index2 : index.getMaterials()) {
				index2.setDrawing_No(index.getDrawing_No());
				index2.setId(index.getId());
			}
			material2s.addAll(index.getMaterials());
		}

		System.err.println(" 物料关系信息去重前" + material2s.size());
		List<Material2> distinctClass = material2s.stream()
				.collect(Collectors.collectingAndThen(
						Collectors.toCollection(
								() -> new TreeSet<>(Comparator.comparing(o -> o.getId() + ";" + o.getMaterial_Code()))),
						ArrayList::new)); // 将物料信息去重
		System.err.println(" 物料关系信息去重后" + distinctClass.size());

		for (int i = 0; i < drawingMaterials.size() / 900 + 1; i++) {// 一次提交所有数据等待时间太久 分割开来提交
			List<DrawingMaterial> index = new ArrayList<DrawingMaterial>();
			if ((i + 1) * 900 > drawingMaterials.size())
				index = drawingMaterials.subList(i * 900, drawingMaterials.size());
			if ((i + 1) * 900 <= drawingMaterials.size())
				index = drawingMaterials.subList(i * 900, (i + 1) * 900);
			if (index.size() > 0) {
				uxmadsMapper.insert_Uxmads(index, projectNumber);
			}
		}
		maxId = uxmadsMapper.select_unifier_uxmads_lieitem_MaxId();
		if (maxId == null) {
			maxId = 1;
		} else {
			maxId++;
		}
		List<Material2> indexs = new ArrayList<Material2>(distinctClass);
		for (int i = 0; i < indexs.size() / 900 + 1; i++) {// 一次提交所有数据等待时间太久 分割开来提交
			List<Material2> index = new ArrayList<Material2>();
			if ((i + 1) * 900 > indexs.size())
				index = indexs.subList(i * 900, indexs.size());
			if ((i + 1) * 900 <= indexs.size())
				index = indexs.subList(i * 900, (i + 1) * 900);
			if (index.size() > 0) {
				uxmadsMapper.insert_Uxmads_lieitem(index, maxId);
				maxId = maxId + index.size();
			}
		}

	}

	/**
	 * 插入图纸物料关联信息
	 *
	 * @param uxmadsMapper
	 * @param drawingMaterials
	 * @param material2s
	 */
	public List<DrawingMaterial> insertdrawingMaterials(Map<String, DrawingMaterial> drawingMaterialsMap,
			String discipline, Integer projectNumber) {
		List<DrawingMaterial> drawingMaterials = new ArrayList<DrawingMaterial>();
		Set<Material2> material2s = new HashSet<Material2>();

		List<String> list = uxmadsMapper.select_unifier_uxmads_Drawing_No(discipline, projectNumber);

		Integer maxId = uxmadsMapper.select_unifier_uxmads_MaxId();

		if (maxId == null) {
			maxId = 1;
		}
		maxId++;

		//循环所有的图纸关联的物料对象信息
		for (DrawingMaterial index : drawingMaterialsMap.values()) { // 将所有的 图纸关联物料对象取出
			System.out.println(index);
			index.setId(maxId);
			drawingMaterials.add(index);
			maxId++;
		}

		System.err.println("图纸物料关系信息去重前" + drawingMaterials.size()); //
		drawingMaterials = drawingMaterials.stream().filter(i -> !list.contains(i.getDrawing_No() + i.getRev()))
				.collect(Collectors.toList());
		System.err.println("图纸物料关系信息去重后" + drawingMaterials.size());

		for (DrawingMaterial index : drawingMaterials) {
			for (Material2 index2 : index.getMaterials()) {
				index2.setDrawing_No(index.getDrawing_No());
				index2.setId(index.getId());
			}
			material2s.addAll(index.getMaterials());
		}

		System.err.println(" 物料关系信息去重前" + material2s.size());
		List<Material2> distinctClass = material2s.stream()
				.collect(Collectors.collectingAndThen(
						Collectors.toCollection(
								() -> new TreeSet<>(Comparator.comparing(o -> o.getId() + ";" + o.getMaterial_Code()))),
						ArrayList::new)); // 将物料信息去重
		System.err.println(" 物料关系信息去重后" + distinctClass.size());

		// 对比出 物料信息是否错误
		List<Integer> drawingId = new ArrayList<Integer>();
		for (Material2 index : distinctClass) {
			int i = 0;
			if ((index.getMaterial_Sort().equals("bulk") || index.getMaterial_Sort().equals("remnant"))) {
				for (Material2 index2 : distinctClass) {
					if ((index2.getMaterial_Sort().equals("bulk") || index2.getMaterial_Sort().equals("remnant"))) {
						if (!index.getDrawing_No().equals(index2.getDrawing_No())) {
							if(index.getBulkMaterialNo()!=null&&index2.getBulkMaterialNo()!=null) {
								if (index.getBulkMaterialNo().equals(index2.getBulkMaterialNo())
										&& index.getMaterial_Code().equals(index2.getMaterial_Code())
										&& index.getMaterial_Sort().equals(index2.getMaterial_Sort())) {

									i++;
								}
							}
						}
					}
				}
			}
			if (i >= 2) {
				drawingId.add(index.getId());
			}

		}

		// 与数据库中 对比出 物料信息是否错误
		List<Map<String, String>> map = uxmadsMapper.select_uxmads_lieitem_remnant_bulk(projectNumber);
		for (Material2 index : distinctClass) {
			int i = 0;
			if ((index.getMaterial_Sort().equals("bulk") || index.getMaterial_Sort().equals("remnant"))) {
				for (Map<String, String> index2 : map) {
					if(index.getBulkMaterialNo()!=null && index2.get("BULK_MATERIAL_NO")!=null) {
						if (index.getBulkMaterialNo().equals(index2.get("BULK_MATERIAL_NO"))
								&& index.getMaterial_Code().equals(index2.get("MATERIAL_CODE"))
								&& index.getMaterial_Sort().equals(index2.get("MATERIAL_SORT"))) {
							if (!index.getDrawing_No().equals(index2.get("Drawing_No"))) {
								i++;
							}
						}
					}
				}
			}
			if (i >= 1) {
				drawingId.add(index.getId());
			}
		}

		List<DrawingMaterial> drawingList = new ArrayList<DrawingMaterial>();
		for (Integer index : drawingId) { // 返回有问题的图纸信息
			for (DrawingMaterial index2 : drawingMaterials) {
				if (index.equals(index2.getId())) {
					drawingList.add(index2);
				}
			}
		}

		// 将有错误的图纸信息 删除
		Iterator<DrawingMaterial> it = drawingMaterials.iterator();
		while (it.hasNext()) {
			DrawingMaterial index = it.next();
			for (Integer index2 : drawingId) {
				if (index2.equals(index.getId())) {
					it.remove();
				}
			}
		}

		// 将有错误的图纸物料信息 删除
		Iterator<Material2> it2 = distinctClass.iterator();
		while (it2.hasNext()) {
			Material2 index = it2.next();
			for (Integer index2 : drawingId) {
				if (index2.equals(index.getId())) {
					it2.remove();
				}
			}
		}

		for (int i = 0; i < drawingMaterials.size() / 900 + 1; i++) {// 一次提交所有数据等待时间太久 分割开来提交
			List<DrawingMaterial> index = new ArrayList<DrawingMaterial>();
			if ((i + 1) * 900 > drawingMaterials.size())
				index = drawingMaterials.subList(i * 900, drawingMaterials.size());
			if ((i + 1) * 900 <= drawingMaterials.size())
				index = drawingMaterials.subList(i * 900, (i + 1) * 900);
			if (index.size() > 0) {
				uxmadsMapper.insert_Uxmads(index, projectNumber);
			}
		}
		maxId = uxmadsMapper.select_unifier_uxmads_lieitem_MaxId();
		if (maxId == null) {
			maxId = 1;
		} else {
			maxId++;
		}
		List<Material2> indexs = new ArrayList<Material2>(distinctClass);
		for (int i = 0; i < indexs.size() / 10 + 1; i++) {// 一次提交所有数据等待时间太久 分割开来提交
			List<Material2> index = new ArrayList<Material2>();
			if ((i + 1) * 10 > indexs.size())
				index = indexs.subList(i * 10, indexs.size());
			if ((i + 1) * 10 <= indexs.size())
				index = indexs.subList(i * 10, (i + 1) * 10);
			if (index.size() > 0) {
				System.err.println(index);
				try {
					uxmadsMapper.insert_Uxmads_lieitem(index, maxId);
				} catch (Exception e) {
					System.err.println(index);
				}

				maxId = maxId + index.size();
			}
		}

		return drawingList;


	}

	/**
	 * 图纸关联物流信息塞入
	 *
	 * @param index
	 * @param DrawingNo
	 * @param DrawingRev
	 * @param type
	 * @return
	 */
	public DrawingMaterial setDrawingMaterial(Map<String, String> index, String DrawingNo, String DrawingRev,
			String discipline, String type) {

		DrawingMaterial drawingMaterial = new DrawingMaterial();
		drawingMaterial.setDrawing_No(DrawingNo);
		drawingMaterial.setRev(DrawingRev);
		drawingMaterial.setType(discipline);
		Set<Material2> material2s = new HashSet<Material2>();
		Material2 material2 = new Material2();
		if (type.equals("fatherDrawing")) {// 预制图
			if (index.get("partNo") != null && !index.get("partNo").equals("NA") && !index.get("partNo").equals(" ")) {
				material2 = new Material2();
				material2.setMaterial_Code(index.get("partNo"));
				material2.setMaterial_Sort("part");
				material2.setTotal_QTY(index.get("qty"));
				material2s.add(material2);
			}
		} else if (type.equals("shopDrawing")) { // 加设图

			if (index.get("assemblyFabricationDetailNo") != null
					&& !index.get("assemblyFabricationDetailNo").equals(" ")
					&& !index.get("assemblyFabricationDetailNo").equals("")
					&& !index.get("assemblyFabricationDetailNo").equals("NA")) {
				material2 = new Material2();
				material2.setMaterial_Code(index.get("assemblyFabricationDetailNo"));
				material2.setMaterial_Sort("fabrication");
				material2.setTotal_QTY(index.get("qty"));
				material2s.add(material2);
			}

		} else if (type.equals("nestingDrawing")) { // 套料图

			if (index.get("partNo") != null && !index.get("partNo").equals("NA") && !index.get("partNo").equals(" ")) {
				material2 = new Material2();
				material2.setMaterial_Code(index.get("partNo"));
				material2.setMaterial_Sort("part");
				material2.setTotal_QTY(index.get("qty"));
				material2s.add(material2);
			}
			if (index.get("remnantPartNo") != null && !index.get("remnantPartNo").equals("")
					&& !index.get("remnantPartNo").equals("整料") && !index.get("remnantPartNo").equals("NA")) {
				material2 = new Material2();
				material2.setMaterial_Code(index.get("remnantPartNo"));
				material2.setMaterial_Sort("remnant");
				material2.setBulkMaterialNo(index.get("bulkMaterialNo"));
				material2.setTotal_QTY(index.get("qty"));
				material2s.add(material2);
			} else if (index.get("materialCode") != null && !index.get("materialCode").equals("NA")
					&& !index.get("materialCode").equals(" ")) {
				material2 = new Material2();
				material2.setMaterial_Code(index.get("materialCode"));
				material2.setTotal_QTY(index.get("qty"));
				material2.setMaterial_Sort("bulk");
				material2.setMtoNo(index.get("MTONo"));
				material2.setBulkMaterialNo(index.get("bulkMaterialNo"));
				material2s.add(material2);
			}

		}

		drawingMaterial.setMaterials(material2s);
		return drawingMaterial;
	}

	/**
	 * 图纸关联物流信息塞入 设备专业
	 *
	 * @param index
	 * @param DrawingNo
	 * @param DrawingRev
	 * @param discipline
	 * @param type
	 * @return
	 */
	public DrawingMaterial setDrawingMaterialMA(Map<String, String> index, String DrawingNo, String DrawingRev,
			String discipline, String type) {

		DrawingMaterial drawingMaterial = new DrawingMaterial();
		drawingMaterial.setDrawing_No(DrawingNo);
		drawingMaterial.setRev(DrawingRev);
		drawingMaterial.setType(discipline);
		Set<Material2> material2s = new HashSet<Material2>();
		Material2 material2 = new Material2();

		if (type.equals("shopDrawing")) { // 加设图
			if (index.get("type").equals("设备")) {
				if (index.get("tagNo") != null && !index.get("tagNo").equals(" ") && !index.get("tagNo").equals("")
						&& !index.get("tagNo").equals("NA")) {
					material2 = new Material2();
					material2.setMaterial_Code(index.get("tagNo"));
					material2.setMaterial_Sort("tag");
					material2.setTotal_QTY(index.get("PurchaseQty"));
					System.err.println(material2);
					material2s.add(material2);
				}
			} else if (index.get("type").equals("母材")) {
				if (index.get("materialCode") != null && !index.get("materialCode").equals("materialCode")
						&& !index.get("materialCode").equals(" ")) {
					material2 = new Material2();
					material2.setMaterial_Code(index.get("materialCode"));
					material2.setMaterial_Sort("bulk");
					material2.setTotal_QTY(index.get("PurchaseQty"));
					material2s.add(material2);
				}

			} else if (index.get("type").equals("附件")) {
				material2 = new Material2();
				material2.setMaterial_Code(index.get("materialCode"));
				material2.setMaterial_Sort("part");
				material2.setTotal_QTY(index.get("PurchaseQty"));
				material2s.add(material2);
			}
		}

		drawingMaterial.setMaterials(material2s);
		return drawingMaterial;
	}

	/**
	 * 图纸关联物料信息塞入
	 *
	 * @param index
	 * @param DrawingNo
	 * @param DrawingRev
	 * @param type
	 * @return
	 */
	public DrawingMaterial setDrawingMaterialPI(Map<String, String> index, String DrawingNo, String DrawingRev,
			String discipline, String type) {

		DrawingMaterial drawingMaterial = new DrawingMaterial();
		drawingMaterial.setDrawing_No(DrawingNo);
		drawingMaterial.setRev(DrawingRev);
		drawingMaterial.setType(discipline);
		Set<Material2> material2s = new HashSet<Material2>();
		Material2 material2 = new Material2();
		if (type.equals("fatherDrawing")) {// 预制图
			if (index.get("partType").equals("FAB")) {
				if (index.get("partNo") != null && !index.get("partNo").equals("NA")
						&& !index.get("partNo").equals(" ")) {
					material2 = new Material2();
					material2.setMaterial_Code(index.get("partNo"));
					material2.setMaterial_Sort("part");
					material2.setTotal_QTY(index.get("qty"));
					material2s.add(material2);
				}
				if (index.get("partNo") == null || index.get("partNo").equals("NA")
						|| index.get("partNo").equals(" ")) {
					material2 = new Material2();
					material2.setMaterial_Code(index.get("materialCode"));
					material2.setMaterial_Sort("bulk");
					material2.setMtoNo(index.get("MTONo"));
					material2.setTotal_QTY(index.get("qty"));
					material2s.add(material2);
				}
			}
		} else if (type.equals("shopDrawing")) { // 加设图
			String fabricationNo = index.get("FabricationNo");
			if (fabricationNo != null && !fabricationNo.equals(" ") && !fabricationNo.equals("")
					&& !fabricationNo.equals("NA")) {
				material2 = new Material2();
				String fabricationDrawingNo = index.get("shopDrawingNo") + "-" + index.get("shopDrawingRev") + "-"
						+ fabricationNo;
				material2.setMaterial_Code(fabricationDrawingNo);
				material2.setMaterial_Sort("fabrication");
				material2.setTotal_QTY(index.get("qty"));
				material2s.add(material2);
			}

			if (fabricationNo == null || fabricationNo.equals("NA") || fabricationNo.equals(" ")) {
				material2 = new Material2();
				material2.setMaterial_Code(index.get("materialCode"));
				material2.setMaterial_Sort("bulk");
				material2.setMtoNo(index.get("MTONo"));
				material2.setTotal_QTY(index.get("qty"));
				material2s.add(material2);
			}

		} else if (type.equals("nestingDrawing")) { // 套料图

			if (index.get("partNo") != null && !index.get("partNo").equals("NA") && !index.get("partNo").equals(" ")) {
				material2 = new Material2();
				material2.setMaterial_Code(index.get("partNo"));
				material2.setMaterial_Sort("part");
				material2.setTotal_QTY(index.get("qty"));
				material2s.add(material2);
			}
			if (index.get("remnantPartNo") != null && !index.get("remnantPartNo").equals("")
					&& !index.get("remnantPartNo").equals("整料") && !index.get("remnantPartNo").equals("NA")) {
				material2 = new Material2();
				material2.setMaterial_Code(index.get("remnantPartNo"));
				material2.setMaterial_Sort("remnant");
				material2.setTotal_QTY(index.get("qty"));
				material2.setBulkMaterialNo(index.get("bulkMaterialNo"));
				material2s.add(material2);
			} else if (index.get("materialCode") != null && !index.get("materialCode").equals("NA")
					&& !index.get("materialCode").equals(" ")) {
				material2 = new Material2();
				material2.setMaterial_Code(index.get("materialCode"));
				material2.setMaterial_Sort("bulk");
				material2.setMtoNo(index.get("MTONo"));
				material2.setTotal_QTY(index.get("qty"));
				material2.setBulkMaterialNo(index.get("bulkMaterialNo"));
				material2s.add(material2);
			}

		}

		drawingMaterial.setMaterials(material2s);
		return drawingMaterial;
	}

	/**
	 * 物料信息去重
	 *
	 * @param index
	 * @param type
	 * @return
	 */
	public List<Map<String, String>> deweightMaterial(Set<Map<String, String>> index, String type, String discipline,
			Integer projectNumber) {
		List<Map<String, String>> data = null;
		List<String> list;
		if (type.equals("bulk")) {
			data = index.stream()
					.collect(Collectors.collectingAndThen(
							Collectors.toCollection(
									() -> new TreeSet<>(Comparator.comparing(o -> o.get("materialCode")))),
							ArrayList::new));

			list = uxpmStck.selectUxpmstck_materialCode_bulk(discipline, projectNumber);
			System.err.println("物料信息去重前" + data.size());
			data = data.stream().filter(it -> !list.contains(it.get("materialCode"))).collect(Collectors.toList());
			System.err.println("物料母材信息去重后" + data.size());

		} else if (type.equals("fabrication")) {
			data = index.stream()
					.collect(Collectors.collectingAndThen(Collectors.toCollection(
							() -> new TreeSet<>(Comparator.comparing(o -> o.get("assemblyFabricationDetailNo")))),
							ArrayList::new));
			list = uxpmStck.selectUxpmstck_materialCode_fabrication(discipline, projectNumber);

			System.err.println("物料信息去重前" + data.size());
			data = data.stream().filter(it -> !list.contains(it.get("materialCode"))).collect(Collectors.toList());
			System.err.println("物料构件信息去重后" + data.size());

		} else if (type.equals("part")) {
			data = new ArrayList<Map<String, String>>(index).stream()
					.collect(Collectors.collectingAndThen(
							Collectors.toCollection(() -> new TreeSet<>(
									Comparator.comparing(o -> o.get("partNo") + ";" + o.get("materialCode")))),
							ArrayList::new)); // 去重
			list = uxpmStck.selectUxpmstck_materialCode_part(discipline, projectNumber);

			System.err.println("物料信息去重前" + data.size());
			data = data.stream().filter(it -> !list.contains(it.get("materialCode") + it.get("partNo")))
					.collect(Collectors.toList());
			System.err.println("物料零件信息去重后" + data.size());

		} else if (type.equals("remnant")) {
			data = new ArrayList<Map<String, String>>(index).stream()
					.collect(Collectors.collectingAndThen(
							Collectors.toCollection(() -> new TreeSet<>(
									Comparator.comparing(o -> o.get("remnantPartNo") + ";" + o.get("materialCode")))),
							ArrayList::new));

			list = uxpmStck.selectUxpmstck_materialCode_remnant(discipline, projectNumber);

			System.err.println("物料信息去重前" + data.size());
			data = data.stream().filter(it -> !list.contains(it.get("materialCode") + it.get("remnantPartNo")))
					.collect(Collectors.toList());
			System.err.println("物料余料信息去重后" + data.size());

		} else if (type.equals("tag")) {
			data = new ArrayList<Map<String, String>>(index).stream()
					.collect(Collectors.collectingAndThen(
							Collectors.toCollection(() -> new TreeSet<>(
									Comparator.comparing(o -> o.get("tagNo") + ";" + o.get("materialCode")))),
							ArrayList::new));

			list = uxpmStck.selectUxpmstck_materialCode_tag(discipline, projectNumber);
			System.err.println("物料信息去重前" + data.size());
			data = data.stream().filter(it -> !list.contains(it.get("tagNo") + it.get("materialCode")))
					.collect(Collectors.toList());
			System.err.println("物料设备信息去重后" + data.size());
		}
		return data;

	}

	/**
	 * 调用原生API插入图纸信息
	 *
	 * @param jobNo
	 *
	 * @param data
	 */
	public void insertDrawing(List<SchedulePlanEngineering> indexs, String jobNo) {
		if (indexs.size() > 0) {
			BPWebService webservice = new BPWebService();
			for (int i = 0; i < indexs.size() / 30 + 1; i++) {// 一次提交所有数据等待时间太久 分割开来提交
				List<SchedulePlanEngineering> index = new ArrayList<SchedulePlanEngineering>();
				if ((i + 1) * 30 > indexs.size())
					index = indexs.subList(i * 30, indexs.size());
				if ((i + 1) * 30 <= indexs.size())
					index = indexs.subList(i * 30, (i + 1) * 30);

				if (index.size() != 0) {
					String xml = ServiceUtil.createXMList(false, XMLHeaderConstants.BP, Drawing.class,
							MapUtils.java2MapList(index));
					xml = XMLResUtil.ResBPExchange(xml, Drawing.class);// 生成XML "TBJN0149"
					System.out.println(xml);
					String mgs = webservice.addBPRecordGeneral(jobNo, "Drawing List", xml); // 图纸原生调用原生接口
					System.err.println(mgs);
				}
			}
		}
	}

	/**
	 * 去重图纸 根据数据库中数据去重
	 *
	 * @param uxenglstMapper
	 * @param shopDrawings
	 * @param nestingDrawings
	 * @param jobNo
	 * @return
	 */
	public List<SchedulePlanEngineering> deweightDrawing(Set<Map<String, String>> shopDrawings,
			Set<Map<String, String>> nestingDrawings, Set<Map<String, String>> fabricationDrawings, String discipline,
			String jobNo) {

		Integer maxId = uxenglstMapper.select_UxenglstMaxID(); // 获取最大ID
		if (maxId == null) {
			maxId = 0;
		}

		Integer projectNumber = projectInfoMapper.select_ProjectNumber(jobNo);

		List<SchedulePlanEngineering> setemps = this.MapToEntity(shopDrawings, nestingDrawings, fabricationDrawings,
				discipline, projectNumber); // 将图纸封装
		System.err.println("图纸去重前：" + setemps.size());
		List<String> list = uxenglstMapper.select_DrawingNo(setemps.get(0).getDiscipline(), projectNumber); // 查出数据库里的图纸信息
		setemps = setemps.stream().filter(i -> !list.contains(i.getDrawing_No() + i.getRev()))
				.collect(Collectors.toList());
		System.err.println("图纸去重后：" + setemps.size());
		for (SchedulePlanEngineering indexData : setemps) {
			maxId++;
			indexData.setId(maxId);
		}

		return setemps;

	}

	/**
	 * 封装 图纸实体类信息
	 *
	 * @param shopDrawings
	 * @param nestingDrawings
	 * @return
	 */
	public ArrayList<SchedulePlanEngineering> MapToEntity(Set<Map<String, String>> shopDrawings,
			Set<Map<String, String>> nestingDrawings, Set<Map<String, String>> fabricationDrawings, String discipline,
			Integer projectNumber) {
		Set<SchedulePlanEngineering> setemps = new HashSet<SchedulePlanEngineering>();
		if (shopDrawings != null) {
			for (Map<String, String> map : shopDrawings) { // 将加设图 转为 java 实体类
				SchedulePlanEngineering indexData = new SchedulePlanEngineering();
				indexData.setDrawing_Category("shop");
				indexData.setDiscipline(discipline);
				indexData.setDrawing_Desc_CN(""); // 图纸中文描述
				indexData.setDrawing_No(map.get("shopDrawingNo"));
				indexData.setRev(map.get("shopDrawingRev"));// 图纸版本号
				indexData.setLine_iNo(map.get("lineNo"));// 管线号
				indexData.setJobcard_install_No(map.get("JobcardInstallNo"));
				indexData.setCompany_Doc_No("");// 公司文档code
				indexData.setModule_Name(map.get("moduleName"));// 模块名称
				indexData.setWork_Package_No(map.get("workPackageNo")); // 工作包code
				indexData.setLoc(map.get("loc"));// 位置
				indexData.setInstallation_Method_PD(map.get("installation_Method_PD"));// 安装方式
				indexData.setConnection_Type_PD(map.get("connection_Type_PD"));// 连接形式
				indexData.setWorking_Procedure("install");
				indexData.setProject_id(projectNumber);
				setemps.add(indexData);
			}
		}
		if (nestingDrawings != null) {
			for (Map<String, String> map : nestingDrawings) { // 将套料图 转为 java 实体类
				SchedulePlanEngineering indexData = new SchedulePlanEngineering();
				indexData.setDrawing_Category("nesting");
				indexData.setDrawing_Desc_CN(""); // 图纸中文描述
				indexData.setDrawing_No(map.get("nestingDrawingNo"));
				indexData.setFather_Drawing_No(map.get("FatherDrawingNo"));
				indexData.setFathe_Drawing_REV(map.get("FabricationDrawingNoRev"));
				indexData.setJobcard_install_No(map.get("JobcardInstallNo"));
				indexData.setDiscipline(discipline);
				indexData.setRev(map.get("nestingDrawingRev"));// 图纸版本号
				indexData.setCompany_Doc_No("");// 公司文档code
				indexData.setModule_Name(map.get("moduleName"));// 模块名称
				indexData.setWork_Package_No(map.get("workPackageNo")); // 工作包code
				indexData.setWorking_Procedure("cut");
				indexData.setInfo_wrong_no(map.get("Info_wrong_no"));
				indexData.setProject_id(projectNumber);
				setemps.add(indexData);
			}

		}
		if (fabricationDrawings != null) {
			for (Map<String, String> map : fabricationDrawings) { // 将构件图 转为 java 实体类
				SchedulePlanEngineering indexData = new SchedulePlanEngineering();
				indexData.setDrawing_Category("fabrication");
				indexData.setDrawing_Desc_CN(""); // 图纸中文描述
				indexData.setDrawing_No(map.get("FabricationDrawingNo"));
				indexData.setRev(map.get("FabricationDrawingNoRev"));// 图纸版本号
				// indexData.setFather_Drawing_No(map.get("fatherDrawingNo"));
				// indexData.setFathe_Drawing_REV(map.get("fatheDrawingRev"));
				indexData.setJobcard_install_No(map.get("JobcardInstallNo"));
				indexData.setLine_iNo(map.get("lineNo"));// 管线号
				indexData.setDiscipline(discipline);
				indexData.setCompany_Doc_No("");// 公司文档code
				indexData.setModule_Name(map.get("moduleName"));// 模块名称
				indexData.setWork_Package_No(map.get("workPackageNo")); // 工作包code
				indexData.setWorking_Procedure("weld");
				indexData.setProject_id(projectNumber);
				setemps.add(indexData);
			}

		}

		return new ArrayList<SchedulePlanEngineering>(setemps).stream()
				.collect(Collectors.collectingAndThen(
						Collectors.toCollection(
								() -> new TreeSet<>(Comparator.comparing(o -> o.getDrawing_No() + ";" + o.getRev()))),
						ArrayList::new));// 去重;

	}

	/**
	 * 某项目应读取的文件路径
	 *
	 * @param projectId
	 * @return
	 */
	public List<String> inquire_ProjectMTRFilePath(Integer projectId, String discipline) {

		ProjectShell projectShell = projectInfoMapper.select_ProjectShellDetail(projectId);

		Calendar ca = Calendar.getInstance();// 得到一个Calendar的实例
		ca.setTime(new Date()); // 设置时间为当前时间
		ca.add(Calendar.DATE, -1); // 日期减1
		Date lastMonth = ca.getTime(); // 结果
		SimpleDateFormat yyyymmDate = new SimpleDateFormat("yyyy-MM");
		SimpleDateFormat yyyyMMddDate = new SimpleDateFormat("yyyyMMdd");
		String yyyyMMdd = yyyyMMddDate.format(lastMonth);
		String yyyymm = yyyymmDate.format(lastMonth);
		String path = null;
		switch (discipline) {
		case "ST":
			path = projectShell.getTrackinglist_Path_ST();
			break;
		default:
			break;
		}
		if (path != null) {
			List<String> fileNames = this.traverseFolder(path + "/" + yyyymm);
			List<String> filePaths = new ArrayList<String>();
			for (String index : fileNames) {
				boolean flag = index.contains(yyyyMMdd);
				if (flag) {
					filePaths.add(path + "/" + yyyymm + "/" + index);
				}

			}

			return filePaths;
		} else {
			return null;
		}
	}

	/**
	 * 某项目应读取的文件路径
	 *
	 * @param projectId
	 * @return
	 */
	public List<String> inquire_ProjectWeldFilePath(Integer projectId, String discipline) {

		ProjectShell projectShell = projectInfoMapper.select_ProjectShellDetail(projectId);
		Calendar ca = Calendar.getInstance();// 得到一个Calendar的实例
		ca.setTime(new Date()); // 设置时间为当前时间
		ca.add(Calendar.DATE, -1); // 日期减1
		Date lastMonth = ca.getTime(); // 结果
		SimpleDateFormat yyyyMMddDate = new SimpleDateFormat("yyyy-MM-dd");
		String yyyyMMdd = yyyyMMddDate.format(lastMonth);
		String path = null;
		switch (discipline) {
		case "ST":
			path = projectShell.getWeld_ST_Path();
			break;
		case "PI":
			path = projectShell.getWeld_ST_Path();
			break;
		}
		if (path != null) {
			List<String> fileNames = this.traverseFolder(path);
			List<String> filePaths = new ArrayList<String>();
			for (String index : fileNames) {
				boolean flag = index.contains(yyyyMMdd);
				if (flag) {
					filePaths.add(path+ "/" + index);
				}

			}

			return filePaths;
		} else {
			return null;
		}
	}



	/**
	 * 读取某路径下所有文件名称
	 *
	 * @param path
	 * @return
	 */
	public List<String> traverseFolder(String path) {
		List<String> fileNames = new ArrayList<String>();
		File file = new File(path);
		if (file.exists()) {
			LinkedList<File> list = new LinkedList<File>();
			list.add(file);
			File[] files;
			while (!list.isEmpty()) {
				files = list.removeFirst().listFiles();
				for (File file1 : files) {
					if (file1.isDirectory()) {
					} else {
						fileNames.add(file1.getName());
					}
				}
			}
		} else {
		}

		return fileNames;

	}

	@SuppressWarnings("unused")
	protected String processResult(XMLObject result) {
		// status: 200 means success ， otherwise failed ...
		if (result.getStatusCode() == 200) {
			return "Success";
		} else {
			String ress = "Failed, ";
			for (String string : result.getErrorStatus()) {
				ress += string;
			}
			return ress;
		}
	}

	public boolean partis(String partName, String structureType) {
		boolean is = true;
		switch (partName) {
		case "FlangeofPGBeam":
			break;
		case "WebPlateofPGBeam":
			break;
		case "insertPlateofFlange":
			break;
		case "insertPlateofWeb":
			break;
		case "LiftingPlate":
			break;
		case "WallK16Plate":
			break;
		case "MainPart":
			switch (structureType) {
			case "PrimaryStructure":

				break;
			case "AccessPlatform":

				break;
			case "SecondaryStructure":

				break;

			default:
				is = false;
				break;
			}
			break;
		case "Handrail":
			break;
		case "Grating":
			break;
		case "Stair":
			break;
		default:
			is = false;
			break;
		}
		return is;
	}

	/**
	 * 插入预制JobcArd
	 *
	 * @param index
	 */
	public void insertJobcArdFabricationPI(String Working_Procedure, SchedulePlanEngineering index,
			List<JobcardWeIdListPI> dataList, JOBCard jobcard, ProjectShell project) {
		// 预制图同时创建 组队与焊接jobcArd
		jobcard.setWorking_Procedure(Working_Procedure);// 为jobcard 选定 工序
		// 查询图纸关联的母材信息

		List<RequiredMaterialDetail> RequiredMaterials = uxpmStck.selectUxpmstck_Drawing_No_bulk(index.getDrawing_No(),
				index.getRev(), project.getProjectObjectid());

		List<PartMaterialDetail> PartMaterials = null;

		if (index.getDrawing_Category().equals("fabrication")) {
			// 查询图纸关联的零件信息
			// PartMaterials =
			// uxpmStck.selectUxpmstck_Drawing_No_Part(index.getDrawing_No(),index.getRev(),
			// project.getProjectObjectid());
		} else if (index.getDrawing_Category().equals("shop")) {
			// 查询图纸关联构件信息
			PartMaterials = uxpmStck.selectUxpmstck_Drawing_No_FabricationPI(index.getDrawing_No(), index.getRev(),
					project.getProjectObjectid());
		}

		// 根据上述数量计算当前材料 准备进展%
		jobcard.setMaterial_Progress("0%");
		jobcard.setMaterial_Status("Preparing");
		this.insertJobcArdAR(index, RequiredMaterials, PartMaterials, dataList, jobcard, project);// 插入创建jobcArd
	}

	public void insertJobcArdFabricationAR(String Working_Procedure, SchedulePlanEngineering index,
										   List<JobcardWeIdListPI> dataList, JOBCard jobcard, ProjectShell project) {
		// 预制图同时创建 组队与焊接jobcArd
		jobcard.setWorking_Procedure(Working_Procedure);// 为jobcard 选定 工序
		// 查询图纸关联的母材信息

		List<RequiredMaterialDetail> RequiredMaterials = uxpmStck.selectUxpmstck_Drawing_No_bulk(index.getDrawing_No(),
				index.getRev(), project.getProjectObjectid());

		List<PartMaterialDetail> PartMaterials = null;
		// 根据上述数量计算当前材料 准备进展%
		jobcard.setMaterial_Progress("0%");
		jobcard.setMaterial_Status("Preparing");
		this.insertJobcArdAR(index, RequiredMaterials, PartMaterials, dataList, jobcard, project);// 插入创建jobcArd
	}

	public void insertJobcArdAR(SchedulePlanEngineering index, List<RequiredMaterialDetail> RequiredMaterials,
								List<PartMaterialDetail> PartMaterials, List<JobcardWeIdListPI> dataList, JOBCard jobcard,
								ProjectShell project) {
		if (webservice == null) {
			webservice = new BPWebService();
		}

		// Get HSE Documents
		// 直接根据项目ID和工序查询
		List<JB2HSSE> listHSSEDocuments = null;
		if (index.getWorking_Procedure() != null) {
			listHSSEDocuments = uxJbcardMapper.listJBHSSEDocuments(index.getProject_id(), index.getWorking_Procedure());
			// HSE LIST 大小>0可评估为该文件已经具备
			jobcard.setHSE_Doc_Status("NA");

			if (listHSSEDocuments.size() > 0) {
				jobcard.setHSE_Doc_Status("isReady");
			}
		}
		// Get QCD Documents
		// 直接根据项目ID和工序查询
		List<JB3QCD> listQCDocuments = null;
		if (index.getWorking_Procedure() != null) {
			listQCDocuments = uxJbcardMapper.listJBQCDDocuments(index.getProject_id(), index.getWorking_Procedure());
			// QCD LIST 大小>0可评估为该文件已经具备
			jobcard.setQC_Doc_Status("NA");
			if (listQCDocuments.size() > 0) {
				jobcard.setQC_Doc_Status("isReady");
			}
		}
		// 创建用用于调用原生接口增加JOBCard记录的XML参数
		// createXMLWithLineItemX4 中 X4代码4个页签
		String xml = ServiceUtil.createXMLWithLineItemX6(false, XMLHeaderConstants.BP, JOBCard.class,
				MapUtils.java2Map(jobcard), RequiredMaterialDetail.class, MapUtils.java2MapList(RequiredMaterials),
				PartMaterialDetail.class, MapUtils.java2MapList(PartMaterials), null, null, JobcardWeIdListPI.class,
				MapUtils.java2MapList(dataList), JB2HSSE.class, MapUtils.java2MapList(listHSSEDocuments), JB3QCD.class,
				MapUtils.java2MapList(listQCDocuments)

		);
		// 对XML格式化首字母，五个对象均需处理
		xml = XMLResUtil.ResBPExchange(xml, JOBCard.class);
		xml = XMLResUtil.ResBPExchange(xml, RequiredMaterialDetail.class);
		xml = XMLResUtil.ResBPExchange(xml, PartMaterialDetail.class);
		// xml = XMLResUtil.ResBPExchange(xml, MaterialPart.class);
		xml = XMLResUtil.ResBPExchange(xml, JB2HSSE.class);
		xml = XMLResUtil.ResBPExchange(xml, JB3QCD.class);
		xml = XMLResUtil.ResBPExchange(xml, JobcardWeIdListPI.class);
		String l = webservice.addBPRecordGeneral(project.getProjectNumber(), "JOBCard List", xml);// 调用原生接口创建JOBc
		// 更新 图纸标识状态，标明该图纸已经对应生成JOBCARD记录
		if (l.equals("Success")) {
			 uxenglstMapper.updateTriggerStatusV2(index.getProject_id(), index.getRecord_no());
		}
		System.err.println(l);
	}


	public void insertJobcArdPI(SchedulePlanEngineering index, List<RequiredMaterialDetail> RequiredMaterials,
			List<PartMaterialDetail> PartMaterials, List<JobcardWeIdListPI> dataList, JOBCard jobcard,
			ProjectShell project) {
		if (webservice == null) {
			webservice = new BPWebService();
		}

		// Get HSE Documents
		// 直接根据项目ID和工序查询
		List<JB2HSSE> listHSSEDocuments = null;
		if (index.getWorking_Procedure() != null) {
			listHSSEDocuments = uxJbcardMapper.listJBHSSEDocuments(index.getProject_id(), index.getWorking_Procedure());
			// HSE LIST 大小>0可评估为该文件已经具备
			jobcard.setHSE_Doc_Status("NA");

			if (listHSSEDocuments.size() > 0) {
				jobcard.setHSE_Doc_Status("isReady");
			}
		}
		// Get QCD Documents
		// 直接根据项目ID和工序查询
		List<JB3QCD> listQCDocuments = null;
		if (index.getWorking_Procedure() != null) {
			listQCDocuments = uxJbcardMapper.listJBQCDDocuments(index.getProject_id(), index.getWorking_Procedure());
			// QCD LIST 大小>0可评估为该文件已经具备
			jobcard.setQC_Doc_Status("NA");
			if (listQCDocuments.size() > 0) {
				jobcard.setQC_Doc_Status("isReady");
			}
		}
		// 创建用用于调用原生接口增加JOBCard记录的XML参数
		// createXMLWithLineItemX4 中 X4代码4个页签
		String xml = ServiceUtil.createXMLWithLineItemX6(false, XMLHeaderConstants.BP, JOBCard.class,
				MapUtils.java2Map(jobcard), RequiredMaterialDetail.class, MapUtils.java2MapList(RequiredMaterials),
				PartMaterialDetail.class, MapUtils.java2MapList(PartMaterials), null, null, JobcardWeIdListPI.class,
				MapUtils.java2MapList(dataList), JB2HSSE.class, MapUtils.java2MapList(listHSSEDocuments), JB3QCD.class,
				MapUtils.java2MapList(listQCDocuments)

		);
		// 对XML格式化首字母，五个对象均需处理
		xml = XMLResUtil.ResBPExchange(xml, JOBCard.class);
		xml = XMLResUtil.ResBPExchange(xml, RequiredMaterialDetail.class);
		xml = XMLResUtil.ResBPExchange(xml, PartMaterialDetail.class);
		// xml = XMLResUtil.ResBPExchange(xml, MaterialPart.class);
		xml = XMLResUtil.ResBPExchange(xml, JB2HSSE.class);
		xml = XMLResUtil.ResBPExchange(xml, JB3QCD.class);
		xml = XMLResUtil.ResBPExchange(xml, JobcardWeIdListPI.class);
		String l = webservice.addBPRecordGeneral(project.getProjectNumber(), "JOBCard List", xml);// 调用原生接口创建JOBc
		// 更新 图纸标识状态，标明该图纸已经对应生成JOBCARD记录
		if (l.equals("Success")) {
			 uxenglstMapper.updateTriggerStatusV2(index.getProject_id(),
			 index.getRecord_no());
		}
		System.err.println(l);
	}

	/**
	 * 插入预制JobcArd
	 *
	 * @param index
	 */
	public void insertJobcArdFabricationST(String projectNumber, String Working_Procedure,
			SchedulePlanEngineering index, JOBCard jobcard, List<JobcardWeIdListST> dataList) {
		// 预制图同时创建 组队与焊接jobcArd
		jobcard.setWorking_Procedure(Working_Procedure);// 为jobcard 选定 工序
		// 查询物料库存即时库存数据
		// 根据draw（ 图纸编号和版本）找到母材，关联即时库存表进而查询得到
		List<MaterialPart> materialParts = uxpmStck.selectUxpmstck_Drawing_No_Part(index.getDrawing_No(),
				index.getRev(), index.getProject_id());
		// 根据上述数量计算当前材料 准备进展%

		jobcard.setMaterial_Progress("0%");

		jobcard.setMaterial_Status("Preparing");

		insertJobcArdAR(projectNumber, index, jobcard, null, null, materialParts, null, dataList);// 插入创建jobcArd
	}

	/**
	 * 插入JobcardAR
	 *
	 * @param projectNumber
	 * @param index
	 * @param jobcard
	 * @param listMaterial
	 * @param partList
	 * @param dataList
	 */
	public void insertJobcArdAR(String projectNumber, SchedulePlanEngineering index, JOBCard jobcard,
			List<PartMaterialDetail> partMaterialDetails, List<RequiredMaterialDetail> requiredMaterials,
			List<MaterialPart> materialParts, List<SurplusMaterial> surplusMaterials,
			List<JobcardWeIdListST> dataList) {

		List<JB2HSSE> list = new ArrayList<JB2HSSE>();
		JB2HSSE entity = null;
		// Get HSE Documents
		// 直接根据项目ID和工序查询
		List<JB2HSSE> listHSSEDocuments = uxJbcardMapper.listJBHSSEDocuments(index.getProject_id(),
				index.getWorking_Procedure());
		if (listHSSEDocuments.size() > 0) {
			for (int i = 0; i < listHSSEDocuments.size(); i++) {
				entity = new JB2HSSE();
				entity.setCompany_Doc_No(listHSSEDocuments.get(i).getADD_DOCUMENT_NUMBER());
				entity.setDocument_No(listHSSEDocuments.get(i).getJSA_NO());
				entity.setDocument_Name(listHSSEDocuments.get(i).getADD_DOCUMENT_NAME());
				entity.setRev(listHSSEDocuments.get(i).getVERSION_NUMBER());
				list.add(entity);
			}

		}
		// HSE LIST 大小>0可评估为该文件已经具备
		jobcard.setHSE_Doc_Status("NA");

		if (listHSSEDocuments.size() > 0) {
			jobcard.setHSE_Doc_Status("isReady");
		}
		// Get QCD Documents
		// 直接根据项目ID和工序查询
		List<JB3QCD> listQCDocuments = uxJbcardMapper.listJBQCDDocuments(index.getProject_id(),
				index.getWorking_Procedure());
		if (listQCDocuments.size() > 0) {
			List<JB3QCD> list2 = new ArrayList<JB3QCD>();
			JB3QCD entity2 = null;
			for (int j = 0; j < listQCDocuments.size(); j++) {
				entity2 = new JB3QCD();
				entity2.setCompany_Doc_No(listQCDocuments.get(j).getVENDOR_DOCUMENT_NO());
				entity2.setDocument_No(listQCDocuments.get(j).getVENDOR_DOCUMENT_NO());
				entity2.setDocument_Name(listQCDocuments.get(j).getVENDOR_DOCUMENT_TITLE());
				entity2.setRev(listQCDocuments.get(j).getREV());
				list2.add(entity2);

			}
		}
		// QCD LIST 大小>0可评估为该文件已经具备
		jobcard.setQC_Doc_Status("NA");
		if (listQCDocuments.size() > 0) {
			jobcard.setQC_Doc_Status("isReady");
		}

		// 创建用用于调用原生接口增加JOBCard记录的XML参数
		// createXMLWithLineItemX5 中 X5代码5个页签
		// PartMaterials 所需零件列表 RequiredMaterials所需余料列表 MaterialParts产生母材列表

		String xml = ServiceUtil.createXMLWithLineItemX7(false, XMLHeaderConstants.BP, JOBCard.class,
				MapUtils.java2Map(jobcard), // jobcard主体信息
				PartMaterialDetail.class, MapUtils.java2MapList(null), // 产生零件页签
				RequiredMaterialDetail.class, MapUtils.java2MapList(requiredMaterials), // 所需母材信息
				MaterialPart.class, MapUtils.java2MapList(null), // 所需零件信息
				SurplusMaterial.class, MapUtils.java2MapList(null), // 所需余料信息
				JobcardWeIdListST.class, MapUtils.java2MapList(dataList), JB2HSSE.class, MapUtils.java2MapList(null),
				JB3QCD.class, MapUtils.java2MapList(null));
		// 对XML格式化首字母，7个对象均需处理
		xml = XMLResUtil.ResBPExchange(xml, JOBCard.class);
		xml = XMLResUtil.ResBPExchange(xml, PartMaterialDetail.class);
		xml = XMLResUtil.ResBPExchange(xml, RequiredMaterialDetail.class);
		xml = XMLResUtil.ResBPExchange(xml, MaterialPart.class);
		xml = XMLResUtil.ResBPExchange(xml, SurplusMaterial.class);
		xml = XMLResUtil.ResBPExchange(xml, JobcardWeIdListST.class);
		// xml = XMLResUtil.ResBPExchange(xml, JB2HSSE.class);
		// xml = XMLResUtil.ResBPExchange(xml, JB3QCD.class);
		BPWebService webservice = new BPWebService();
		String l = webservice.addBPRecordGeneral(projectNumber, BPConstants.JOBCARD, xml);// 调用原生接口创建JOBc
		// 更新 图纸标识状态，标明该图纸已经对应生成JOBCARD记录
		System.err.println(xml);
		System.err.println(l);
		if (l.equals("Success")) {
			uxenglstMapper.updateTriggerStatusV2(index.getProject_id(), index.getRecord_no());
		}

	}

	/**
	 * 插入JobcardMA
	 *
	 * @param index
	 * @param RequiredMaterials
	 * @param PartMaterials
	 * @param jobcard
	 * @param project
	 */
	@SuppressWarnings("unchecked")
	public void insertJobcArdMA(SchedulePlanEngineering index, List<RequiredMaterialDetail> RequiredMaterials,
			List<PartMaterialDetail> PartMaterials, List<JobcardWeIdListMA> dataList, JOBCard jobcard,
			ProjectShell project) {
		if (webservice == null) {
			webservice = new BPWebService();
		}

		// Get HSE Documents
		// 直接根据项目ID和工序查询
		List<JB2HSSE> listHSSEDocuments = null;
		if (index.getWorking_Procedure() != null) {
			listHSSEDocuments = uxJbcardMapper.listJBHSSEDocuments(index.getProject_id(), index.getWorking_Procedure());
			// HSE LIST 大小>0可评估为该文件已经具备
			jobcard.setHSE_Doc_Status("NA");

			if (listHSSEDocuments.size() > 0) {
				jobcard.setHSE_Doc_Status("isReady");
			}
		}
		// Get QCD Documents
		// 直接根据项目ID和工序查询
		List<JB3QCD> listQCDocuments = null;
		if (index.getWorking_Procedure() != null) {
			listQCDocuments = uxJbcardMapper.listJBQCDDocuments(index.getProject_id(), index.getWorking_Procedure());
			// QCD LIST 大小>0可评估为该文件已经具备
			jobcard.setQC_Doc_Status("NA");
			if (listQCDocuments.size() > 0) {
				jobcard.setQC_Doc_Status("isReady");
			}
		}
		// 创建用用于调用原生接口增加JOBCard记录的XML参数
		// createXMLWithLineItemX4 中 X4代码4个页签
		String xml = ServiceUtil.createXMLWithLineItemX5(false, XMLHeaderConstants.BP, JOBCard.class,
				MapUtils.java2Map(jobcard), RequiredMaterialDetail.class, MapUtils.java2MapList(RequiredMaterials),
				PartMaterialDetail.class, MapUtils.java2MapList(PartMaterials), JB2HSSE.class,
				MapUtils.java2MapList(null), JB3QCD.class, MapUtils.java2MapList(null), JobcardWeIdListMA.class,
				MapUtils.java2MapList(dataList));
		// 对XML格式化首字母，五个对象均需处理
		xml = XMLResUtil.ResBPExchange(xml, JOBCard.class);
		xml = XMLResUtil.ResBPExchange(xml, RequiredMaterialDetail.class);
		xml = XMLResUtil.ResBPExchange(xml, PartMaterialDetail.class);
		xml = XMLResUtil.ResBPExchange(xml, JobcardWeIdListMA.class);
		xml = XMLResUtil.ResBPExchange(xml, JB2HSSE.class);
		xml = XMLResUtil.ResBPExchange(xml, JB3QCD.class);
		System.err.println(xml);
		String l = webservice.addBPRecordGeneral(project.getProjectNumber(), "JOBCard List", xml);// 调用原生接口创建JOBc
		// 更新 图纸标识状态，标明该图纸已经对应生成JOBCARD记录
		if (l.equals("Success")) {
			// uxenglstMapper.updateTriggerStatusV2(index.getProject_id(),
			// index.getRecord_no())
		}
		System.err.println(l);
	}

	/**
	 * 将预工作包发给管线套料插件
	 *
	 * @param jsonObject
	 */
	@SuppressWarnings("unused")
	protected void doUpload(JSONObject jsonObject) {
		CloseableHttpClient client = HttpClients.createDefault();
		// http://172.16.5.122:65147/BomescMaterial/UploadPackages
		// https://bomesc.cjcls.cn:61507/BomescMaterial/UploadPackages
		String url = "https://bomesc.cjcls.cn:61507/BomescMaterial/UploadPackages";// 外部接口地址
		HttpPost post = new HttpPost(url);
		JSONObject response = null;
		try {
			// buildSamDto(sampleDTO)方法为给实体对象sampleDTO属性赋值，
			// 接着用JSONObject.fromObject()方法将该sampleDTO对象转成json
			StringEntity s = new StringEntity(jsonObject.toString());
			s.setContentEncoding("UTF-8");
			s.setContentType("application/json");
			post.setEntity(s);
			post.addHeader("content-type", "application/json");

			HttpResponse res = client.execute(post);// 上报数据
			if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				// String result = EntityUtils.toString(res.getEntity(), "utf-8"); 这个方法只能用一次，
				// 不然会Attempted read from closed stream，故而改用下面的方法。
				// 具体可查看我这篇博客'https://blog.csdn.net/qq_39380155/article/details/109576795'
				byte[] byteArray = EntityUtils.toByteArray(res.getEntity());
				response = JSONObject.fromObject(new String(byteArray, "utf-8"));// 防止返回结果中文乱码
				String message = (String) response.get("message");
				int status = (int) response.get("status");

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	/*
	 * 图纸关联物流信息塞入 舾装专业
	 *
	 * @param index
	 * @param DrawingNo
	 * @param DrawingRev
	 * @param discipline
	 * @param type
	 * @return
	 */
	public DrawingMaterial setDrawingMaterialAR(Map<String, String> index, String DrawingNo, String DrawingRev,
											  String discipline, String type) {

		DrawingMaterial drawingMaterial = new DrawingMaterial();
		drawingMaterial.setDrawing_No(DrawingNo); //图纸编号
		drawingMaterial.setRev(DrawingRev); //图纸版本
		drawingMaterial.setType(discipline); //图纸专业
		Set<Material2> material2s = new HashSet<Material2>();
		Material2 material2 = new Material2();
		  if (type.equals("shopDrawing")) { // 加设图
				material2 = new Material2();
				material2.setMaterial_Code(index.get("materialCode"));
				material2.setMaterial_Sort("bulk");
				material2.setTotal_QTY(index.get("qty"));
				material2.setDrawing_No(DrawingNo);
				material2s.add(material2);

		}
		drawingMaterial.setMaterials(material2s);
		return drawingMaterial;
	}


	public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
		Map<Object, Boolean> seen = new ConcurrentHashMap<>();
		return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
	}

	/**
	 * 插入JobcardST
	 *
	 * @param projectNumber
	 * @param index
	 * @param jobcard
	 * @param listMaterial
	 * @param partList
	 * @param dataList
	 */
	public void insertJobcArdST(String projectNumber, SchedulePlanEngineering index, JOBCard jobcard,
								List<PartMaterialDetail> partMaterialDetails, List<RequiredMaterialDetail> requiredMaterials,
								List<MaterialPart> materialParts, List<SurplusMaterial> surplusMaterials,
								List<JobcardWeIdListST> dataList) {

		List<JB2HSSE> list = new ArrayList<JB2HSSE>();
		JB2HSSE entity = null;
		// Get HSE Documents
		// 直接根据项目ID和工序查询
		List<JB2HSSE> listHSSEDocuments = uxJbcardMapper.listJBHSSEDocuments(index.getProject_id(),
				index.getWorking_Procedure());
		if (listHSSEDocuments.size() > 0) {
			for (int i = 0; i < listHSSEDocuments.size(); i++) {
				entity = new JB2HSSE();
				entity.setCompany_Doc_No(listHSSEDocuments.get(i).getADD_DOCUMENT_NUMBER());
				entity.setDocument_No(listHSSEDocuments.get(i).getJSA_NO());
				entity.setDocument_Name(listHSSEDocuments.get(i).getADD_DOCUMENT_NAME());
				entity.setRev(listHSSEDocuments.get(i).getVERSION_NUMBER());
				list.add(entity);
			}

		}
		// HSE LIST 大小>0可评估为该文件已经具备
		jobcard.setHSE_Doc_Status("NA");

		if (listHSSEDocuments.size() > 0) {
			jobcard.setHSE_Doc_Status("isReady");
		}
		// Get QCD Documents
		// 直接根据项目ID和工序查询
		List<JB3QCD> listQCDocuments = uxJbcardMapper.listJBQCDDocuments(index.getProject_id(),
				index.getWorking_Procedure());
		if (listQCDocuments.size() > 0) {
			List<JB3QCD> list2 = new ArrayList<JB3QCD>();
			JB3QCD entity2 = null;
			for (int j = 0; j < listQCDocuments.size(); j++) {
				entity2 = new JB3QCD();
				entity2.setCompany_Doc_No(listQCDocuments.get(j).getVENDOR_DOCUMENT_NO());
				entity2.setDocument_No(listQCDocuments.get(j).getVENDOR_DOCUMENT_NO());
				entity2.setDocument_Name(listQCDocuments.get(j).getVENDOR_DOCUMENT_TITLE());
				entity2.setRev(listQCDocuments.get(j).getREV());
				list2.add(entity2);

			}
		}
		// QCD LIST 大小>0可评估为该文件已经具备
		jobcard.setQC_Doc_Status("NA");
		if (listQCDocuments.size() > 0) {
			jobcard.setQC_Doc_Status("isReady");
		}

		// 创建用用于调用原生接口增加JOBCard记录的XML参数
		// createXMLWithLineItemX5 中 X5代码5个页签
		// PartMaterials 所需零件列表 RequiredMaterials所需余料列表 MaterialParts产生母材列表

		String xml = ServiceUtil.createXMLWithLineItemX7(false, XMLHeaderConstants.BP, JOBCard.class,
				MapUtils.java2Map(jobcard), // jobcatd主体信息
				PartMaterialDetail.class, MapUtils.java2MapList(partMaterialDetails), // 产生零件页签
				RequiredMaterialDetail.class, MapUtils.java2MapList(requiredMaterials), // 所需母材信息
				MaterialPart.class, MapUtils.java2MapList(materialParts), // 所需零件信息
				SurplusMaterial.class, MapUtils.java2MapList(surplusMaterials), // 所需余料信息
				JobcardWeIdListST.class, MapUtils.java2MapList(dataList), JB2HSSE.class, MapUtils.java2MapList(null),
				JB3QCD.class, MapUtils.java2MapList(null));
		// 对XML格式化首字母，7个对象均需处理
		xml = XMLResUtil.ResBPExchange(xml, JOBCard.class);
		xml = XMLResUtil.ResBPExchange(xml, PartMaterialDetail.class);
		xml = XMLResUtil.ResBPExchange(xml, RequiredMaterialDetail.class);
		xml = XMLResUtil.ResBPExchange(xml, MaterialPart.class);
		xml = XMLResUtil.ResBPExchange(xml, SurplusMaterial.class);
		xml = XMLResUtil.ResBPExchange(xml, JobcardWeIdListST.class);
		// xml = XMLResUtil.ResBPExchange(xml, JB2HSSE.class);
		// xml = XMLResUtil.ResBPExchange(xml, JB3QCD.class);
		BPWebService webservice = new BPWebService();
		String l = webservice.addBPRecordGeneral(projectNumber, BPConstants.JOBCARD, xml);// 调用原生接口创建JOBc
		// 更新 图纸标识状态，标明该图纸已经对应生成JOBCARD记录
		System.err.println(xml);
		System.err.println(l);
		if (l.equals("Success")) {
			uxenglstMapper.updateTriggerStatusV2(index.getProject_id(), index.getRecord_no());
		}

	}


}
